package com.erebus.submit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erebus.base.model.PageParams;
import com.erebus.base.model.RestResponse;
import com.erebus.submit.mapper.StudentMapper;
import com.erebus.submit.mapper.TeacherMapper;
import com.erebus.submit.mapper.WorkRecordMapper;
import com.erebus.submit.mapper.WorkReleaseMapper;
import com.erebus.submit.model.dto.MyWorkDto;
import com.erebus.submit.model.po.Student;
import com.erebus.submit.model.po.Teacher;
import com.erebus.submit.model.po.WorkRecord;
import com.erebus.submit.model.po.WorkRelease;
import com.erebus.submit.service.UpFileService;
import com.erebus.submit.utils.SRSG;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class UpFileServiceImpl implements UpFileService {

    @Autowired
    MinioClient minioClient;
    //存储文件
    @Value("${minio.bucket.files}")
    private String bucket_files;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private WorkReleaseMapper workReleaseMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private WorkRecordMapper workRecordMapper;



    @Override
    public RestResponse<ArrayList<MyWorkDto>> list(PageParams pageParams, String studentId) {

        Student student = studentMapper.selectByStudentId(studentId);

        String classId = student.getClassId();

        // 根据班级id查询所有作业
        LambdaQueryWrapper<WorkRelease> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(StringUtils.isNotEmpty(classId), WorkRelease::getClassId, classId);
        List<WorkRelease> workReleases = workReleaseMapper.selectList(queryWrapper);

        ArrayList<MyWorkDto> myWorkDtoList = new ArrayList<>();

        for(WorkRelease workRelease : workReleases){
            MyWorkDto myWorkDto = new MyWorkDto();

            myWorkDto.setWorkName(workRelease.getWorkName());
            myWorkDto.setTxt(workRelease.getTxt());
            myWorkDto.setSubject(workRelease.getSubject());
            myWorkDto.setUpDate(workRelease.getUpDate());
            myWorkDto.setEndDate(workRelease.getEndDate());
            myWorkDto.setTeacherName(byTeacherIdName(workRelease.getTeacherId()));
            myWorkDtoList.add(myWorkDto);
        }

        return RestResponse.success(myWorkDtoList);
    }

    @Override
    public String upFile(String studentId, String localFilePath, String fileName) {

        //先得到扩展名
        String extension = fileName.substring(fileName.lastIndexOf("."));

        //得到mimeType
        String mimeType = getMimeType(extension);

        //子目录
        String defaultFolderPath = getDefaultFolderPath();

        //使用默认年月日去存储
        String objectName = defaultFolderPath  + fileName;

        System.out.println(objectName);


        try {
            UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder()
                    .bucket(bucket_files)//桶
                    .filename(localFilePath) //指定本地文件路径
                    .object(objectName)//对象名 放在子目录下
                    .contentType(mimeType)//设置媒体文件类型
                    .build();
            //上传文件
            minioClient.uploadObject(uploadObjectArgs);
            log.debug("上传文件到minio成功");

            // 文件id
            String workId = SRSG.generateRandomString(16);

            // 当前时间
            LocalDateTime now = LocalDateTime.now();

            Boolean aBoolean = addFilesToDb(studentId, workId, bucket_files, objectName, now);
            
            return "yes";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件出错");
        }
        return null;
    }

    // 上传文件到minio
    private Boolean upFileToMinio(){

        return true;
    }

    // 记录上传记录
    private Boolean addFilesToDb(String studentId, String workId, String bucket, String objectName, LocalDateTime update){

        WorkRecord workRecord = new WorkRecord();
        workRecord.setStudentId(studentId);
        workRecord.setWorkId(workId);

        String filePath = bucket + objectName;
        workRecord.setPath(filePath);
        workRecord.setUpDate(update);

        int i = 0;
        i = workRecordMapper.insert(workRecord);

        if(i == 1){
            return true;
        }

        return false;
    }

    //获取文件默认存储目录路径 年/月/日
    private String getDefaultFolderPath() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String folder = sdf.format(new Date()).replace("-", "/") + "/";
        return folder;
    }

    //根据扩展名获取mimeType
    private String getMimeType(String extension) {
        if (extension == null) {
            extension = "";
        }
        //根据扩展名取出mimeType
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;//通用mimeType，字节流
        if (extensionMatch != null) {
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;
    }

    // 根据教师id获取教师名字
    private String byTeacherIdName(String teacherId){
        Teacher teacher = teacherMapper.byIdName(teacherId);

        return teacher.getName();
    }

}
